<?php

namespace Beerus\Modules\DesignerList\Actions;

use Doraemon\cache\Queue;
use Doraemon\model\AdmOperateLog;
use Doraemon\model\Member;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Doraemon\model\Designer;
use Doraemon\service\search\DesignerSearch;
use Doraemon\service\Designer\DesignerService;
use Doraemon\cache\User as CacheUser;

class ChangeMainArea extends RowAction
{
    public $name = '变更主要服务地区';

    public function handle($uid,Request $request)
    {
//        $new_main_area = $request->get('area');

        //根据area获取这个城市的lid;
//        $area_info = Area::getArea($new_main_area);
//        $lid = $area_info[1];

        $city_name = $request->get('area');
        $main_area_code = Region::getCodeByName($city_name);

        if (empty($main_area_code)) {
	        return $this->response()->error('城市名称输入错误，变更主要服务地区失败,请稍后重试!');
        }

        $data['main_area_code'] = $main_area_code;
        $data['main_area_name'] = $city_name;
        $data['main_area'] = Region::getOldCodeByCode($main_area_code) ?? '';

        //更新设计师表中的主要服务地区数据
//        $data['main_area'] = $lid;
        $result = Designer::updateDesigner($uid,$data);
        //清除用户缓存
	    CacheUser::deleteUserInfo($uid);
        //更新ES数据
        DesignerSearch::updateDesignerByUid($uid);
        DesignerService::updateDesignerEsInfo($uid);
        if ($result){
            return $this->response()->success('变更设计师主要服务地区成功!')->refresh();
        }else{
            return $this->response()->error('变更主要服务地区失败,请稍后重试!');
        }
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $uid = $request->uid;
        //获取该设计师的主要服务地区
        $designer_info = Designer::getInfo($uid);

        $this->text('area', '请输入变更的主要服务地区')->default($designer_info['main_area_name']);

    }
}
